/**
 * Summary: js脚本所能执行的函数空间
 * Version 1.0
 * Date: 13-11-20
 * Time: 下午4:40
 * Copyright: Copyright (c) 2013
 */

package com.xl.rentkeeper.web;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.webkit.WebView;
import android.widget.Toast;

import com.xl.fuse.protos.account.Sk;
import com.xl.fuse.protos.account.SkIner;
import com.xl.rentkeeper.App;
import com.xl.rentkeeper.business.ConfigLogic;
import com.xl.rentkeeper.business.SecurityLogic;
import com.xl.rentkeeper.business.UserLogic;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.mgr.ThreadManager;
import com.xl.rentkeeper.util.AndroidUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okio.ByteString;

//HostJsScope中需要被JS调用的函数，必须定义成public static，且必须包含WebView这个参数
public class HostApp {

    public static void getImei(WebView webView,JsCallback jsCallback) {
        String imei =  ((TelephonyManager) webView.getContext().getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
        jsCallback.apply(imei);
    }

    public static String getSk(WebView webView) {
        if (UserLogic.getInstance().isLogin()) {
            long ts = ConfigLogic.getInstance().getServerTs();
            SkIner iner = new SkIner.Builder().uin(UserLogic.getInstance().getUid()).ts(ts).ver(1).build();
            byte[] data = iner.toByteArray();
            try {
                byte[] encIner = SecurityLogic.getInstance().encodeDataUseSessionKey(data);
                Sk sk = new Sk.Builder().uin(UserLogic.getInstance().getUid()).data(ByteString.of(encIner)).imei(AndroidUtil.getIMEI(webView.getContext())).build();
                byte[] skData = sk.toByteArray();
                String skStr = Base64.encodeToString(skData,Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
                QLog.d("HostApp","sk:"+skStr+" len:"+skStr.length()+ " iner:"+iner);
                return skStr;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static void delayJsCallback(WebView view, Object l,Object str,Object d, final JsCallback jsCallback) {
        QLog.d("HostApp","l:"+Util.toLong(l)+" d:"+Util.toDouble(d));
        ThreadManager.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                jsCallback.apply("data from java");
            }
        },0);
    }
}